import { Game } from '../game';
import { GameObject } from '../gameObjects/gameObject';
import { Tween }from '../tween/tween';

export class Scene {
  private tweens: Tween[] = [];

  game: Game;

  gameObjects: GameObject[] = [];

  constructor (game: Game) {
    this.game = game;

    this.initScene();
  }

  private async initScene() {
    await this.init();
    await this.preload();
    await this.create();
  }

  public async init () { }

  public async preload () { }

  public async create () { }

  public update (elapsedTime: number) {
    for (const gameObject of this.gameObjects) {
      gameObject.update(elapsedTime);
    }

    for (const tween of this.tweens) {
      tween.update(elapsedTime);
    }
  }

  public render (canvasCtx: CanvasRenderingContext2D) {
    for (const gameObject of this.gameObjects) {
      canvasCtx.save();
      gameObject.render(canvasCtx);
      canvasCtx.restore();
    }
  }

  public add (gameObject: GameObject) {
    this.gameObjects.push(gameObject);
  }

  public addTween(tween: Tween) {
    this.tweens.push(tween);
  }

  public remove (gameObject: GameObject) {
    const index = this.gameObjects.findIndex(el => el === gameObject);
    if (index !== -1) {
      this.gameObjects.splice(index, 1);
    }
  }

  public removeTween(tween: Tween) {
    const index = this.tweens.findIndex(el => el === tween);
    if (index !== -1) {
      this.tweens.splice(index, 1);
    }
  }
}
